<template>
  <div>
    <header class="app-header">宝典</header>
    <!-- {{num}} -->
    <div class="core-container">
      <div class="scroll-wrapper" ref="scroll">
        <div class="pulldown-bswrapper" ref="bsWrapper">
          <div class="pulldown-scroller">
            <div class="pulldown-wrapper">
              <div v-show="beforePullDown">
                <span>Pull Down and refresh</span>
              </div>
              <div v-show="!beforePullDown">
                <div v-show="isPullingDown">
                  <span>Loading...</span>
                </div>
                <div v-show="!isPullingDown">
                  <span>Refresh success</span>
                </div>
              </div>
            </div>
            <div class="scroll-content">
              <div class="scroll-item" data-type="0" v-for="(item, index) in list" :key="index">
                <div class="studys" @touchstart.capture="touchStart" @touchend.capture="touchEnd" @click="skip(item)">
                  <div :class="{study:styleList.includes(item.id)}">{{item.title}}</div>
                </div>
                <div class="del" @click="del(item)">删除</div>
              </div>
            </div>
            <div class="pullup-tips">
              <div>
                <div v-if="!isPullUpLoad" class="before-trigger">
                  <span class="pullup-txt">Pull up and load more</span>
                </div>
                <div v-else class="after-trigger">
                  <span class="pullup-txt">Loading...</span>
                </div>
              </div>
              <!-- <div>
                <span class="pullup-txt">nomore...</span>
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <detail v-if="isDetail" :items="items"/> -->
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from 'vuex'
// import detail from '@/views/msbd/detail.vue'
import BScroll from '@better-scroll/core'
import PullDown from '@better-scroll/pull-down'
import Pullup from '@better-scroll/pull-up'

BScroll.use(Pullup)
BScroll.use(PullDown)
export default {
  name: 'msbd',
  data () {
    return {
      beforePullDown: true,
      isPullingDown: false,
      isPullUpLoad: false,
      // page: this.num /this.currentPage,
      // saveTop: {}
      y: 0,
      isDetail: false,
      items: {},
      startX: 0,
      endX: 0,
    }
  },
  async mounted () {
    // console.log(this.form)
    await this.getStudyBdid()
    this.init()
    await this.getList()
    this.bs.refresh()
    this.initBscroll()
    // this.SET_TOTAL(this.items)
  },
  computed: {
    ...mapState('msbd', ['list', 'currentPage']),
    ...mapState('login', ['form', 'styleList'])
  },
  beforeDestroy () {
    this.bs.destroy()
    // sessionStorage.removeItem('y')
  },
  methods: {
    checkSlide () {
      let listItems = document.querySelectorAll('.scroll-item');
      for (let i = 0; i < listItems.length; i++) {
        if (listItems[i].dataset.type == 1) {
          return true;
        }
      }
      return false;
    },
    async del (item) {
      // console.log(item.id)
      await this.deleteMsbd({ id: item.id })
      this.getList()
    },
    touchStart (e) {
      // console.log(e)
      this.startX = e.touches[0].clientX;
    },
    touchEnd (e) {
      // console.log(e)
      let parentElement = e.currentTarget.parentElement;
      // 记录结束位置
      this.endX = e.changedTouches[0].clientX;
      // 左滑
      if (parentElement.dataset.type == 0 && this.startX - this.endX > 30) {
        // console.log()
        // this.$refs.a[0].style.overflow=''
        this.restSlide();
        parentElement.dataset.type = 1;
      }
      // 右滑
      if (parentElement.dataset.type == 1 && this.startX - this.endX < -30) {
        this.restSlide();
        parentElement.dataset.type = 0;
      }
      this.startX = 0;
      this.endX = 0;
    },
    restSlide () {
      let listItems = document.querySelectorAll('.scroll-item');
      // 复位
      for (let i = 0; i < listItems.length; i++) {
        listItems[i].dataset.type = 0;
      }
    },
    skip (item) {
      if (this.checkSlide()) {
        this.restSlide();
      } else {
        this.clickHandler(item)
      }
    },
    initBscroll () {
      this.bscroll = new BScroll(this.$refs.bsWrapper, {
        scrollY: true,
        // startY: sessionStorage.getItem('y') * 1 || 0,
        bounceTime: 800,
        pullUpLoad: true,
        pullDownRefresh: {
          threshold: 70,
          stop: 55
        }
      })
      this.bscroll.on('pullingUp', this.pullingUpHandler)
      this.bscroll.on('pullingDown', this.pullingDownHandler)
      this.bscroll.on('scrollEnd', ({ y }) => {
        // console.log('scrollEnd')
        // console.log(y)
        this.y = y
        // sessionStorage.setItem('y', this.y)
      })
    },
    async pullingUpHandler () {   ///加载
      this.isPullUpLoad = true
      this.SET_CURRENT_PAGE(this.currentPage + 1)
      await this.getList()
      this.bscroll.finishPullUp()
      this.bscroll.refresh()
      // this.isPullUpLoad = true
      this.isPullUpLoad = false
      // this.pullingDownHandler()
    },
    async pullingDownHandler () {    //刷新
      this.beforePullDown = false
      this.isPullingDown = false
      await this.SET_ADD_PAGE()
      this.bscroll.finishPullUp()
      this.bscroll.refresh()
      this.finishPullDown()
    },
    async finishPullDown () {
      this.isPullingDown = true     //loading
      this.SET_CURRENT_PAGE(0)
      // this.SET_ADD_PAGE(0)
      await this.getList()
      this.isPullingDown = false     //refresh success
      setTimeout(() => {
        this.bscroll.finishPullDown()   //finish pulldown
      }, 800)
      setTimeout(() => {
        this.beforePullDown = true      //pullup  to refresh
      }, 1000)
    },
    ...mapActions('msbd', ['getList', 'getLikesData', 'deleteMsbd']),
    ...mapActions('login', ['getStudyBdid']),
    ...mapMutations('msbd', ['SET_CURRENT_PAGE', 'SET_ADD_PAGE']),
    init () {
      this.bs = new BScroll(this.$refs.scroll, {
        probeType: 3,
        click: true
      })
      this.bs.on('scroll', ({ y }) => {
        // console.log('scrolling-')
      })
      this.bs.on('scrollEnd', ({ y }) => {
        // console.log('scrollingEnd-' + y)
      })
    },
    async clickHandler (item) {    //点击
      // window.alert(item.content)
      // this.saveTop = event.target
      // this.items=item
      // this.isDetail=true
      // this.$router.push({path:'/detail',query:{id:item.id}})
      await this.$router.push('/detail/' + item.id)
      // await this.getLikesData({})
      // this.$router.push({ name: 'Detail', params: { item } })
    },
    // saveTopFun () {
    //   if (this.saveTop) {
    //     this.saveTop.marginTop = this.eventTop.offsetHeight
    //   }
    // }
  },
  activated () {
    // this.saveTopFun()
  },
  components: {
    // detail
  }
}
</script>

<style scoped>
/*滚动*/
.core-container .scroll-wrapper {
  height: calc(100vh - 120px);
  overflow: hidden;
}
.core-container .scroll-wrapper .scroll-item {
  height: 50px;
  line-height: 50px;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  text-align: left;
  /* overflow: hidden; */
  text-overflow: ellipsis;
  white-space: nowrap;
  text-indent: 10px;
  border-bottom: 1px solid #ccc;
  width: 100%;
  margin: auto;
  position: relative;
}

.core-container .scroll-wrapper .scroll-item .study {
  color: #999999;
}

.core-container .scroll-wrapper .scroll-item {
  background-color: #f3f5f7;
}

/*上拉刷新样式*/

.pulldown {
  height: 100%;
}

.scroll-content {
  overflow: hidden;
}

.pulldown-bswrapper {
  position: relative;
  height: 100%;
  padding: 0 20px;
  overflow: hidden;
}

.pulldown-list {
  padding: 0;
}

.pulldown-list-item {
  padding: 10px 0;
  list-style: none;
  border-bottom: 1px solid #ccc;
}

.pulldown-wrapper {
  position: absolute;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  transform: translateY(-100%) translateZ(0);
  text-align: center;
  color: #999;
}

/*加载*/
.pullup {
  height: 100%;
}

.pullup-wrapper {
  height: 100%;
  padding: 0 10px;
  border: 1px solid #ccc;
  overflow: hidden;
}

.pullup-list {
  padding: 0;
}

.pullup-list-item {
  padding: 10px 0;
  list-style: none;
  border-bottom: 1px solid #ccc;
}

.pullup-tips {
  padding: 20px;
  text-align: center;
  color: #999;
}

.studys {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

.del {
  position: absolute;
  background-color: red;
  width: 60px;
  top: 0;
  right: -60px;
  color: white;
  font-size: 15px;
  text-align: center;
}

.scroll-item[data-type='0'] {
  transform: translate3d(0, 0, 0);
}
.scroll-item[data-type='1'] {
  transform: translate3d(-60px, 0, 0);
}

.scroll-item {
  position: relative;
  height: 1.6rem;
  -webkit-transition: all 0.2s;
  transition: all 0.2s;
}
</style>